package com.laikan.reader.apirequester;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.BookRecommendBean;
import com.laikan.reader.core.bean.ClickToSupportBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/19.
 */
public class BookDesRequester {

    public static void clickToSupport(final View view, final String reviewId, final int eventId) {
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    refredhLikeCount(null, false, eventId);
                    return;
                }
                Gson gson = new Gson();
                Type type = new TypeToken<ClickToSupportBean>() {}.getType();
                ClickToSupportBean result = null;
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (null == result || !Constants.RESULT_OK.equals(result.getResult()) || result.getInterActionBean() == null) {
                        ToastMgr.showLongToast(result.getError_msg());
                        refredhLikeCount(null, false, eventId);
                    }else {
                        ImageView clickToSupport = (ImageView)((RelativeLayout)view).findViewById(R.id.iv_clicktosupport);
                        TextView likeCount = (TextView)((RelativeLayout)view).findViewById(R.id.tv_clicktosupport);
                        if(!TextUtils.isEmpty(result.getInterActionBean().getLikeCount()) && result.getInterActionBean().getLikeCount().length() > 2){
                            likeCount.setText(R.string.tv_comment_more);
                        }else {
                            likeCount.setText(result.getInterActionBean().getLikeCount());
                        }
//                        likeCount.setText(result.getInterActionBean().getLikeCount());
                        if (result.getInterActionBean().getFavor()) {
                            clickToSupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable
                                .iv_click_to_support), Color
                                .parseColor("#66ccdd"))));
                        }else {
                            clickToSupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable.iv_click_to_support), Color.parseColor("#999999"))));
                        }
                        refredhLikeCount(result.getInterActionBean().getLikeCount(), result.getInterActionBean().getFavor(), eventId);
                        scaleAnimation(clickToSupport);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    refredhLikeCount(null, false, eventId);
                }
                KLog.e("click json " + httpResponse.responseContent);

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showLongToast(R.string.fw_return_data_error);
                refredhLikeCount(null, false,eventId );
            }

            @Override
            public void onFinish() {
            }

            public void refredhLikeCount(String totalLikeCount, boolean isFavor, int eventId){
                LaiKanEvent event = LaiKanEvent.getInstance();
                event.setEventID(eventId);
                Map<String, Object> mapEvent = new HashMap<>();
                mapEvent.put("totallikecount", totalLikeCount);
                mapEvent.put("replyId",reviewId);
                mapEvent.put("isFavor", isFavor);
                BasicApplication.postEvent(event.setEventMap(mapEvent));
            }

            private void scaleAnimation(View view) {
                //初始化
                Animation scaleAnimation = new ScaleAnimation(0.1f, 1.0f, 0.1f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                //设置动画时间
                scaleAnimation.setDuration(500);
                scaleAnimation.setFillAfter(false);
                view.startAnimation(scaleAnimation);
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_clicktosupport + reviewId + "/like");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    public static void replaceBookRecommend(String bookId, final String sorts) {

        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    noticeRefreshBookRecommend(null, "datafailed");
                    return;
                }
                Gson gson = new Gson();
                Type type = new TypeToken<BookRecommendBean>() {}.getType();
                BookRecommendBean result = null;
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (null == result || !Constants.RESULT_OK.equals(result.getResult()) || result.getRecommendBook() == null) {
                        noticeRefreshBookRecommend(null, "datafailed");
                    }else {
                        noticeRefreshBookRecommend(result.getRecommendBook(), "success");
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
                KLog.e("click json " + httpResponse.responseContent);

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                noticeRefreshBookRecommend(null, "netfailed");
            }

            @Override
            public void onFinish() {

            }

            public void noticeRefreshBookRecommend(BookRecommendBean.RecommendBook bookRecommendBean, String status){
                LaiKanEvent event = LaiKanEvent.getInstance();
                event.setEventID(LaiKanEvent.EVENT_ID_BOOK_REFRESH_RECOMMENDBOOK);
                Map<String, Object> mapEvent = new HashMap<>();
                mapEvent.put("recommendbook", bookRecommendBean);
                mapEvent.put("status", status);
                BasicApplication.postEvent(event.setEventMap(mapEvent));
            }
        };
        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL3() + bookId + "/recommend?sorts=" + sorts);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester,requestListener);
//        HttpApiRequestEngine.getInstance().httpGetRequest(APIProtocol.test_url3 + bookId + "/recommend?sorts=" + sorts,  null, null, requestListener);
    }
}
